package com.tigase.controller;

import com.tigase.bean.TigaseFile;
import com.tigase.service.FileService;
import com.tigase.utils.FianlMessage;
import com.tigase.utils.GetUserIp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tigase.utils.FianlMessage.FILEPATH;

/**
 * Created by tianfeng on 2017/7/12.
 */
@Controller
@RequestMapping("/file")
public class UpOrDownController {
    @Autowired
    private FileService FileService;
    @RequestMapping(value = "/uploads", method = RequestMethod.GET)
    public String upload() {
        return "/fileupload";
    }

    // 访问路径为：http://ip:port/upload/batch
    @RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
    public String batchUpload() {
        return "/mutifileupload";
    }
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> upload(HttpServletRequest request,String from,String to,String path,@RequestParam("file") MultipartFile file,HttpServletResponse HttpServletResponse) {
        HttpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
       String name= file.getOriginalFilename();
       int type=name.lastIndexOf(".");
       String types= name.substring(type+1
       );
        String size= file.getSize()+"";
        String ip=GetUserIp.getUserIp(request);
        Map<String,Object> map=new HashMap<>();
        if (!file.isEmpty()) {
            String relPath=FILEPATH+path;
            // 如果目录不存在则创建
            File uploadDir = new File(relPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(uploadDir+"\\"+name)));
                out.write(file.getBytes());
                out.flush();
                out.close();
                Map<String,String> maps=new HashMap<>();
                TigaseFile oFile=new TigaseFile();
                maps.put("size",size);
                maps.put("name",name);
                maps.put("type",types);
                maps.put("url","http://192.168.0.115/"+path+"/"+name);
                map.put("msg","上传成功");
                map.put("result",maps);
                map.put("flag",true);
                oFile.setFileName(name);
                oFile.setFileSize(size);
                oFile.setFileType(types);
                oFile.setSendFrom(from);
                oFile.setSendTo(to);
                oFile.setPath("http://192.168.0.115/"+path+"/"+name);

                FileService.insertFile(oFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                map.put("msg","上传失败");
                map.put("flag",false);
                return map;
            } catch (IOException e) {
                e.printStackTrace();
                map.put("msg","上传失败");
                map.put("flag",false);
                return map;
            }
            return map;
        } else {
            map.put("msg","上传失败，文件为空");
            map.put("flag",false);
            return map;
        }
    }



    /**
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     *
     * @param request
     * @return
     *
     * @author
     * @create
     */
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public @ResponseBody String batchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        return "upload successful";
    }

    /**
     * 文件下载
     */


    @RequestMapping(value = "/Download", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> testDownload(HttpServletResponse res,String name,HttpServletResponse HttpServletResponse) {
        HttpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        Map<String,Object> map=new HashMap<>();
        String fileName = name;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;

        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("F:\\nginx\\qq\\"
                    + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        map.put("msg","下载成功");
        map.put("flag",true);
        return map;

    }






}
